package game;

import game.module.account.LoginGameHandler10002;
import game.module.account.LoginRequest;
import game.module.role.SayHelloReq;

import java.util.HashMap;
import java.util.Map;

import lion.codec.IClientDispatcher;
import lion.core.GameClient;
import lion.message.MyRequestMsg;
import lion.netty.NettyClient;
import lion.processor.ClientHandler;

import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GameClientV2 implements IClientDispatcher {

	private static Logger logger = LoggerFactory.getLogger(GameClientV2.class);

	private GameClient gameClient;

	private Map<Integer, ClientHandler> clientHandlerMap = new HashMap<Integer, ClientHandler>();

	public GameClientV2() {
		NettyClient amf3Client = new NettyClient(this);
		gameClient = new GameClient(amf3Client);
		gameClient.connect("127.0.0.1", 8653);
		initClientHandlers();
	}

	private void initClientHandlers() {
		clientHandlerMap.put(10002, new LoginGameHandler10002());
	}

	public GameClient getGameClient() {
		return gameClient;
	}

	public static void main(String[] args) {
		ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
		logger.info("spring init success!,factory={}", factory);
		GameClientV2 gameClientV2 = new GameClientV2();
		GameClient gameClient = gameClientV2.getGameClient();
		LoginRequest lr = new LoginRequest(15, 16);
		logger.info("sendtime:{}",System.currentTimeMillis());
		gameClient.send(lr);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		SayHelloReq req = new SayHelloReq();
		gameClient.send(req);
	}

	@Override
	public void executeInPool(Channel channel, MyRequestMsg request) {
		int msgCode = request.getMsgCode();
		ClientHandler clientHandler = clientHandlerMap.get(msgCode);
		if (clientHandler != null) {
			clientHandler.handle(channel, request);
		} else {
			logger.warn("could not find hanlder for={}", msgCode);
		}
	}

}
